"""
    @Author  ：思念 
    @File    ：5.将B站数据写入到CSV中.py
    @Date    ：2024/12/11 16:10 
"""
import requests
import csv

url = 'https://api.bilibili.com/x/web-interface/wbi/search/type?category_id=&search_type=video&ad_resource=5654&__refresh__=true&_extra=&context=&page={}&page_size=42&pubtime_begin_s=0&pubtime_end_s=0&from_source=&from_spmid=333.337&platform=pc&highlight=1&single_column=0&keyword=%E7%BE%8E%E5%A5%B3&qv_id=JgdWbbufmgsQTSoE1mAxBB3mSfu8OLwM&source_tag=3&gaia_vtoken=&dynamic_offset=30&web_location=1430654&w_rid=e210222dbd887725635d4ae3bab771d2&wts=1733904642'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',
    'Cookie': 'buvid3=0DCA2842-F54A-9750-476D-AD1C4C45E5C256985infoc; b_nut=1729423156; _uuid=104106FBB10-523E-5639-96AC-87CC13B83E5657139infoc; enable_web_push=DISABLE; home_feed_column=5; browser_resolution=1699-907; buvid4=770A9ABE-55AC-CCB0-3FDF-CA86B3FCEA4757798-024102011-DnBQxwgV60XcIj%2FwsIiGGlrMpzbfCaDh%2B7aRYfNTXufto169%2BO93ejCcBZBEidQe; DedeUserID=399381719; DedeUserID__ckMd5=70edb25a9c9761db; rpdid=0zbfVGhzHL|Olq56enl|4EL|3w1T2tYq; fingerprint=dab3c933058dcd6cce0babb6d564ec42; buvid_fp_plain=undefined; header_theme_version=CLOSE; buvid_fp=dab3c933058dcd6cce0babb6d564ec42; CURRENT_QUALITY=80; CURRENT_BLACKGAP=0; LIVE_BUVID=AUTO4417305570852511; PVID=1; bp_t_offset_399381719=1006342869318893568; b_lsid=22555F910_193B4BF45EF; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzQxNjM0NTQsImlhdCI6MTczMzkwNDE5NCwicGx0IjotMX0.YQwMh1SMawnjSPjt_iSKrN95R3TWE3VRPqZZCidjK7A; bili_ticket_expires=1734163394; SESSDATA=5322fcbc%2C1749456257%2C84647%2Ac1CjCw9tanmYl605enOK1Xan-GQCHl6RWdnW39I6j3S_S5OHeFJShkbbLoyOHZ9RANOFkSVktSbm5IWVdiOHlXdGVxaUxCaEJVQVp4XzVQQ3pSaGJ1Q2hsZ1IyUW1MdnUwdGFGeDdqUnFZMGw5dGptWi1XdW42Uk5aa0Qxbm1kU0x2ZWphSmdGU0FnIIEC; bili_jct=f700d0aa721a93bba3345661087b5985; sid=86miur1o; CURRENT_FNVAL=2000'
}


def save_data(url):
    file_names = ['title', 'author']
    with open('../bilibili.csv', 'w', newline='', encoding='utf-8') as f:
        f_csv = csv.DictWriter(f, file_names)
        f_csv.writeheader()
        for page in range(1, 2):
            response = requests.get(url.format(page), headers=headers).json()
            for temp in response['data']['result']:
                temp_dict = dict()
                temp_dict['title'] = temp['title']
                temp_dict['author'] = temp['author']
                print(temp_dict)
                f_csv.writerow(temp_dict)


save_data(url)
print('over')


